<template>  
  <div class="container">  
    <div class="main">  
      <div class="header">  
        <el-button type="primary" @click="add">新建</el-button>  
        <el-select v-model="selectedFilter" placeholder="请选择状态">  
          <el-option label="启用" value="1"></el-option>  
          <el-option label="禁用" value="0"></el-option>  
        </el-select>  
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" />  
        <el-button type="info" @click="query">查询</el-button>  
        <el-button type="info" @click="query">重置</el-button>  
      </div>  

      <el-table :data="tableData" border class="eltable">  
        <el-table-column prop="role_id" label="序号" width="80"></el-table-column>  
        <el-table-column prop="role_name" label="角色名称" ></el-table-column>  
        <el-table-column prop="role_notes" label="描写" ></el-table-column>
        <el-table-column prop="role_status" label="启用">
          <template #default="{ row }">
            <el-switch :model-value="row.role_status === 1" @click="onStatusChange(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-tooltip content="编辑" placement="top">
                <div class="operation-item" @click="editRow(row)">
                  <el-icon class="operation-icon">
                    <Edit />
                  </el-icon>
                  <span>编辑</span>
                </div>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <div class="operation-item" @click="deleteRow(row)">
                  <el-icon class="operation-icon delete">
                    <Delete />
                  </el-icon>
                  <span>删除</span>
                </div>
              </el-tooltip>
            </el-space>
          </template>
        </el-table-column> 
      </el-table>  
      <el-pagination  
        @current-change="handleCurrentChange"  
        :current-page="currentPage"  
        :page-size="pageSize"  
        :total="totalItems"  
        layout="total, prev, pager, next, jumper">  
      </el-pagination>  
    </div>  
  </div>  
  <el-dialog v-model="dialogVisible"
                title="添加"
                width="600"
                :before-close="handleClose">
        <span>
          <el-form :model="form" class="demo-form-inline">
            <el-form-item label="名称:" :label-width="formLabelWidth" >
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="说明:" :label-width="formLabelWidth" >
              <el-input v-model="form.notes" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addqr">确 定</el-button>
        </span>
    </el-dialog>
    <el-dialog v-model="xgdialogVisible"
                title="修改"
                width="600"
                :before-close="handleClose">
                <span>
          <el-form :model="xgform" class="demo-form-inline">
            <el-form-item label="名称:" :label-width="formLabelWidth" >
              <el-input v-model="xgform.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="说明:" :label-width="formLabelWidth" >
              <el-input v-model="xgform.notes" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="xgqr">确 定</el-button>
        </span>
    </el-dialog>
</template>  

<script>  
import { ref, reactive, router,computed } from 'vue';  
import axios from 'axios'
import CryptoJS from 'crypto-js';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {  
  setup() {  
    const searchKey = ref('');  
    const treeData = ref([]);  
    const defaultProps = {  
      children: 'children',  
      label: 'label',  
    };  
    //加密方法
    function md5Encrypt(str) {
      return CryptoJS.MD5(str).toString();
    }
    //获取登录角色数据
    const uid=computed(()=>{
           return sessionStorage.getItem('u');
    })
    let yhid=reactive({
            id:uid
    })
    const tableData = ref([]);  

    const selectedFilter = ref('');  
    const searchTable = ref('');  
    const currentPage = ref(1);  
    const pageSize = ref(2);  
    const totalItems = ref(0);  
    let dialogVisible=ref(false);
    let xgdialogVisible=ref(false);
    let form=reactive({
      name:'',
      notes:'',
      uid:yhid.id
    })
    let xgform=reactive({
      rid:'',
      name:'',
      notes:'',
      uid:yhid.id
    })
    const add = () => {  
      // 添加逻辑  
      dialogVisible.value=true;
    };  
    async function addqr(){
      console.log("form")
      try {
        const response =await axios.post('/api/Role/PostRole',{
          role_name:form.name,
          role_notes:form.notes,
          role_create_by:form.uid
        });
        if(response.data){
           ElMessage.error("添加成功");
          dialogVisible.value=false;
          SX();
        }else{
           ElMessage.error("添加失败");
        }
      } catch (error) {
        console.error("请求错误:", error);
         ElMessage.error("服务器错误，请稍后重试。");
      }
    }
    async function SX () {  
      // 查询逻辑  
      try {
        const response = await axios.get('/api/Role/GetFYRole?PageNumber='+currentPage.value+'&PageSize='+pageSize.value);
        tableData.value=response.data.role;
        totalItems.value=response.data.zon;
      } catch (error) {
        console.error("请求错误:", error);
         ElMessage.error("服务器错误，请稍后重试。");
      }
    };  
    SX();
    async function query () {  
      //查询逻辑  
      try {
        const response = await axios.get('/api/Role/GetFYMHRole?PageNumber='+currentPage.value+'&PageSize='+pageSize.value+'&state='+selectedFilter.value+'&uname='+searchTable.value);
        tableData.value=response.data.role;
        totalItems.value=response.data.zon;
      } catch (error) {
        console.error("请求错误:", error);
         ElMessage.error("服务器错误，请稍后重试。");
      }
    };  
    const editRow = (row) => {
      xgdialogVisible.value=true;  
      xgform.rid=row.role_id;
      xgform.name=row.role_name;
      xgform.notes=row.role_notes;
    }; 
    //修改逻辑 
    async function xgqr(){
      try {
        const response =await axios.put('/api/Role/UpdateRole',{
          role_id:xgform.rid,
          role_name:xgform.name,
          role_notes:xgform.notes,
          role_update_by:xgform.uid
        });
        if(response.data){
           ElMessage.error("修改成功");
          xgdialogVisible.value=false;
          SX();
        }else{
           ElMessage.error("修改失败");
        }
      } catch (error) {
        console.error("请求错误:", error);
         ElMessage.error("服务器错误，请稍后重试。");
      }
    }
    //删除逻辑
    async function deleteRow(row){  
      try {
        if (confirm("确定要删除吗？")) {
          const response =await axios.delete('/api/Role/DeleteRole?id='+row.role_id);
          if(response.data){
             ElMessage.error("删除成功");
            dialogVisible.value=false;
            SX();
          }else{
             ElMessage.error("删除失败");
          }
        }
      } catch (error) {
        console.error("请求错误:", error);
         ElMessage.error("服务器错误，请稍后重试。");
      } 
    };  

    const handleCurrentChange = (page) => {  
      currentPage.value = page;  
      // 分页逻辑  
      SX();
    };  
    //修改状态
    const onStatusChange = async (row) => {
      const updatedStatus = row.role_status === 1 ? 0 : 1;
      try {
        await axios.put('/api/Role/UpdateRoleZT?id='+row.role_id+'&state='+updatedStatus);
        row.role_status = updatedStatus; // 更新本地状态  
        ElMessage.success('状态更新成功');
      } catch (error) {
        console.error('状态更新失败:', error);
        ElMessage.error('状态更新失败');
      }
    };
    // 确保所有函数都被返回  
    return {  
      searchKey,  
      treeData,  
      defaultProps,  
      tableData,  
      selectedFilter,  
      searchTable,  
      currentPage,  
      pageSize,  
      totalItems,  
      add,  
      query,  
      editRow,  
      deleteRow,  
      handleCurrentChange, 
      dialogVisible ,
      form,
      addqr,
      xgform,
      xgdialogVisible,
      xgqr,
      onStatusChange
    };  
  },  
  methods: {
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      }
    }
};  
</script>  

<style>  
.container {  
  display: flex;  
  gap: 20px;
  height: 95%;
}  

.sidebar {  
  height: 100%;
  
}  

.main {  
  width: 80%;
  flex: 1;  
  height: 100%;
}  

.header {  
   display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}  
.eltable{
  height: 95%;
}
.letree{
  height: 100%;
}
.demo-form-inline .el-input {
  --el-input-width: 500px;
}

.demo-form-inline .el-select {
  --el-select-width: 200px;
}
</style>